package edu.uoc.tdp.pac3.server;

import java.io.IOException;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;

import javax.swing.JOptionPane;

import edu.uoc.tdp.pac3.common.StockManagerInterface;
import edu.uoc.tdp.pac3.server.impl.StockManagerImpl;
import edu.uoc.tdp.pac3.ui.i18n.LanguageUtils;

public class Server {
	private final int PORT = 1099;
	private final String JNDI_NAME = "StockManager";
	private StockManagerInterface objetoRemoto = null;
	private Registry registry = null;
	
	public static void main(String args[]) throws IOException {
		new Server();
	}

	public Server() {
		try {
			System.out.println("Starting server RMI Server...");
			registry = LocateRegistry.createRegistry(PORT);
			objetoRemoto = new StockManagerImpl();
			registry.rebind(JNDI_NAME, objetoRemoto);
			System.out.println("RMI Server initiated!");
		} catch (RemoteException e) {
			JOptionPane.showMessageDialog(null, 
					LanguageUtils.getMessage("client.error.message.remote"),
					LanguageUtils.getMessage("client.error.title"),
					JOptionPane.ERROR_MESSAGE);
		} catch (Exception e) {
			JOptionPane.showMessageDialog(null, 
					LanguageUtils.getMessage("client.error.message.generic"),
					LanguageUtils.getMessage("client.error.title"),
					JOptionPane.ERROR_MESSAGE);
		}
	}
	
	public void stopServer() {  
        try {  
            System.out.println("Uninstalling Service.........");  
            registry.unbind(JNDI_NAME);  
            System.out.println("Unbound.");  
            UnicastRemoteObject.unexportObject(objetoRemoto, true);  
            System.out.println("obj unexported.");  
            UnicastRemoteObject.unexportObject(registry, true);  
            System.out.println("registry unexported.");  
        } catch (RemoteException ex) {  
        	JOptionPane.showMessageDialog(null, 
					LanguageUtils.getMessage("client.error.message.remote"),
					LanguageUtils.getMessage("client.error.title"),
					JOptionPane.ERROR_MESSAGE);
        } catch (NotBoundException ex) {  
        	JOptionPane.showMessageDialog(null, 
					LanguageUtils.getMessage("client.error.message.remote.bound"),
					LanguageUtils.getMessage("client.error.title"),
					JOptionPane.ERROR_MESSAGE); 
        }  
    }  
}